<template>
  <page-dialog
    :title="props.type == 'add' ? '新增' : '修改'"
    v-model:visible="shows"
    :width="dialogInfo.width"
    :bt-list="dialogInfo.btList"
  >
    <!-- 条件栏 -->
    <NewPageFilter
      v-if="props.type == 'add'"
      v-model:query="filterInfo.query.queryMap"
      :filter-list="filterInfo.searchList"
      :filter-btn="filterInfo.searchBtn"
      :list-type-info="listTypeInfo"
      style="float: left"
    />
    <!-- 条件栏 -->
    <NewPageFilter
      v-if="props.type == 'add'"
      v-model:query="filterInfo2.query.queryMap"
      :filter-list="filterInfo2.searchList"
      :filter-btn="filterInfo2.searchBtn"
      style="float: left; margin-left: 10px"
    >
      <!-- 约定量期间开始 periodStart -->
      <!-- 约定量期间结束 periodEnd -->
      <template v-slot:filter-periodStart="scope">
        <el-date-picker
          v-model="filterInfo2.query.periodStart"
          type="date"
          value-format="YYYY-MM-DD"
          placeholder="选择约定量期间开始日期"
        >
        </el-date-picker>
      </template>
      <template v-slot:filter-periodEnd="scope">
        <el-date-picker
          v-model="filterInfo2.query.periodEnd"
          type="date"
          value-format="YYYY-MM-DD"
          placeholder="选择约定量期间结束日期"
        >
        </el-date-picker>
      </template>
    </NewPageFilter>
    <el-form ref="assetAmortizationDeptTableForm" :model="tableInfo">
      <DialogTable
        :refresh="tableInfo.refresh"
        :init-curpage="tableInfo.initCurpage"
        v-model:data="tableInfo.data"
        :api="api"
        ref="resourceTable"
        :query="filterInfo.query.queryMap"
        :field-list="tableInfo.fieldList"
        :handle="tableInfo.handle"
        :highlight-row="highlightRow"
        :checked-list="checkedList"
        :reserve-selection="true"
        :check-box="props.type == 'add' ? checkBox : false"
        :pager="props.type == 'add' ? true : false"
        @handleEvent="handleEvent"
      >
        <template #col-commonName="scope">
          <p>{{ scope.row.commonName || '-' }}</p>
          <p>{{ scope.row.productCode || '-' }}</p>
          <p>{{ scope.row.alias || '-' }}</p>
        </template>
        <template #col-standard="scope">
          <p>{{ scope.row.standard || '-' }}</p>
          <p>{{ scope.row.unitName || '-' }}</p>
        </template>
        <template #col-type="scope">
          <p>{{ scope.row.productTypeValue || '-' }}</p>
          <p>{{ scope.row.codeTypeValue || '-' }}</p>
          <p>{{ scope.row.productCategoryValue || '-' }}</p>
        </template>
        <template #col-supplierName="scope">
          <p>{{ scope.row.supplierName || '-' }}</p>
        </template>
        <template #col-licenseNumber="scope">
          <p>{{ scope.row.licenseNumber || '-' }}</p>
          <p>{{ scope.row.brandName || '-' }}</p>
        </template>
        <!-- 约定量期间开始 periodStart -->
        <!-- 约定量期间结束 periodEnd -->
        <template v-slot:col-periodStart="scope">
          <el-form-item
            @click.stop=""
            :prop="`data.${scope.$index}.periodStart`"
            :rules="[
              {
                required:
                  scope.$index >= 0 &&
                  (selectRowIds.includes(scope.row.id) || type == 'update'),
                message: '请选择约定量期间开始',
                trigger: 'change',
              },
            ]"
          >
            <el-date-picker
              v-model="scope.row.periodStart"
              type="date"
              value-format="YYYY-MM-DD"
              placeholder="选择约定量期间开始日期"
            >
            </el-date-picker>
          </el-form-item>
        </template>
        <template v-slot:col-periodEnd="scope">
          <el-form-item
            @click.stop=""
            :prop="`data.${scope.$index}.periodEnd`"
            :rules="[
              {
                required:
                  scope.$index >= 0 &&
                  (selectRowIds.includes(scope.row.id) || type == 'update'),
                message: '请选择约定量期间结束日期',
                trigger: 'change',
              },
            ]"
          >
            <el-date-picker
              v-model="scope.row.periodEnd"
              type="date"
              value-format="YYYY-MM-DD"
              placeholder="选择约定量期间结束日期"
            >
            </el-date-picker>
          </el-form-item>
        </template>
        <!-- 约定采购量 agreeLimit -->
        <template v-slot:col-agreeLimit="scope">
          <el-form-item
            @click.stop=""
            :prop="`data.${scope.$index}.agreeLimit`"
            :rules="[
              {
                required:
                  scope.$index >= 0 &&
                  (selectRowIds.includes(scope.row.id) || type == 'update'),
                message: '请输入约定采购量',
                trigger: 'blur',
              },
            ]"
          >
            <el-input-number
              v-model.lazy="scope.row.agreeLimit"
              clearable
              controls-position="right"
              :precision="2"
              :min="0"
              :max="highLimit"
              @change="preparationDoseChange($event, scope.row, scope.$index)"
            />
          </el-form-item>
        </template>
        <!-- 转换比 -->
        <template v-slot:col-unitRatio="scope">
          <el-form-item
            @click.stop=""
            :prop="`data.${scope.$index}.unitRatio`"
            :rules="[
              {
                required:
                  scope.$index >= 0 &&
                  (selectRowIds.includes(scope.row.id) || type == 'update'),
                message: '请输入规格转换比',
                trigger: 'blur',
              },
            ]"
          >
            <el-input-number
              v-model.lazy="scope.row.unitRatio"
              clearable
              controls-position="right"
              :precision="2"
              :min="0"
              :max="highLimit"
              @change="preparationDoseChange($event, scope.row, scope.$index)"
            />
          </el-form-item>
        </template>
        <!-- 制剂单位 -->
        <template v-slot:col-preparationUnit="scope">
          <el-form-item
            @click.stop=""
            :prop="`data.${scope.$index}.preparationUnit`"
            :rules="[
              {
                required:
                  scope.$index >= 0 &&
                  (selectRowIds.includes(scope.row.id) || type == 'update'),
                message: '请输入制剂单位',
                trigger: 'blur',
              },
            ]"
          >
            <el-select clearable v-model="scope.row.preparationUnit">
              <el-option
                v-for="item in listTypeInfo.unitList"
                :key="item.value"
                :value="item.value"
                :label="item.key"
              />
            </el-select>
          </el-form-item>
        </template>
        <!-- 制剂单位 -->
        <template v-slot:col-preparationQty="scope">
          <el-form-item
            @click.stop=""
            :prop="`data.${scope.$index}.preparationQty`"
          >
            <el-input v-model="scope.row.preparationQty" clearable></el-input>
          </el-form-item>
        </template>
      </DialogTable>
    </el-form>
  </page-dialog>
</template>
<script setup name="selectProduct">
import { getProductPage, getSupplierAll, getUnitAll } from '@/api/core.js'
import {
  agreeQuantityProductAdd,
  agreeQuantityProductUpdate,
} from '@/api/purch.js'
const { proxy } = getCurrentInstance()
const emits = defineEmits()
let highLimit = ref(99999999)
const props = defineProps({
  highlightRow: {
    type: Boolean,
    default: false,
  },
  checkBox: {
    type: Boolean,
    default: true,
  },
  api: {
    type: Function,
    default: getProductPage,
  },
  showDialog: {
    type: Boolean,
    default: false,
  },
  showSupplierName: {
    type: Boolean,
    default: false,
  },
  type: {
    type: String,
    default: 'add',
  },
  row: {
    type: Object,
    default: {},
  },
  query: {
    type: Object,
    default: function () {
      return {}
    },
  },
  showStock: {
    type: Boolean,
    default: false,
  },
  checkedList: {
    type: Array,
    default: () => {
      return []
    },
  },
})

// 过滤相关配置
const filterInfo = ref({
  query: {
    sortString: '',
    groupMap: {},
    groups: [],
    queryMap: {
      searchType: 'product',
      status: 1,
      type: 0,
      sort: 'common_name,standard',
      ...props.query,
    },
  },
  searchList: [
    {
      componentType: 'input',
      label: '名称/别名/编码/助记符',
      value: 'keyword',
      event: search,
      hidden: false,
      show: true,
    },
    {
      label: '供应商',
      value: 'supplierIdMult',
      componentType: 'slip-select',
      api: getSupplierAll,
      query: { sort: 'create_time desc' },
      clearable: true,
      multiple: true,
      keyField: 'supplierName',
      valueField: 'supplierId',
      event: search,
    },
  ],
  searchBtn: [{ type: 'button', label: '搜索', event: search }],
})
// 批量设置过滤
const filterInfo2 = ref({
  query: {},
  searchList: [
    {
      label: '约定量期间开始日期',
      value: 'periodStart',
      slot: true,
    },
    {
      label: '约定量期间结束日期',
      value: 'periodEnd',
      slot: true,
    },
  ],
  searchBtn: [{ type: 'button', label: '批量设置', event: batchSetting }],
})
// 表格相关
const tableInfo = ref({
  refresh: 1,
  initCurpage: 1,
  data: [],
  fieldList: [
    {
      label: '通用名称\n编码\n别名',
      value: 'commonName',
      minWidth: 220,
      type: 'slot',
    },
    { label: '规格', value: 'standard' },
    {
      label: '规格转换比',
      value: 'unitRatio',
      type: 'slot',
    },
    {
      label: '制剂单位',
      value: 'preparationUnit',
      type: 'slot',
    },
    {
      label: '约定量(制剂)',
      value: 'preparationQty',
      type: 'slot',
    },
    {
      label: '约定量(包装)',
      value: 'agreeLimit',
      type: 'slot',
    },
    { label: '包装单位', value: 'unitName' },
    {
      label: '产品类型\n条码类型\n产品分类',
      value: 'type',
      minWidth: 150,
      type: 'slot',
    },
    { label: '助记符', value: 'mnemonic', width: '100px' },
    {
      label: '证号\n生产厂家',
      value: 'licenseNumber',
      minWidth: 220,
      type: 'slot',
    },
    {
      label: '约定量期间开始日期',
      value: 'periodStart',
      type: 'slot',
    },
    {
      label: '约定量期间结束日期',
      value: 'periodEnd',
      type: 'slot',
    },
  ],
})
const selectRow = ref([])
const selectRowIds = ref([])
// 弹窗相关
const dialogInfo = ref({
  width: '70%',
  btLoading: false,
  btList: [
    { label: '关闭', event: handleClose, show: true },
    {
      label: '保存',
      type: 'primary',
      disabled: false,
      event: save,
      show: true,
    },
  ],
})
const listTypeInfo = ref({
  supplierList: [],
  unitList: [],
})

const shows = computed({
  get() {
    return props.showDialog
  },
  set(newValue) {
    emits('update:showDialog', newValue) // 更新父组件shows
  },
})

watch(
  () => tableInfo.value.data,
  (val) => {
    if (val.length && props.checkedList.length) {
      props.checkedList.forEach((row) =>
        proxy.$refs['resourceTable'].toggleRowSelection(row, true)
      )
    }
  }
)
watch(
  () => selectRowIds.value,
  (val) => {
    console.log(val)
    if (val.length) {
      tableInfo.value.data.map((i) => {
        if (val.includes(i.id)) {
          i['unitRatio'] = i['unitRatio'] || 1
        } else {
          i['unitRatio'] = i['unitRatio'] || ''
        }
      })
    } else {
      tableInfo.value.data.map((i) => {
        i['unitRatio'] = i['unitRatio'] || ''
      })
    }
  },
  {
    deep: true,
  }
)

onMounted(() => {
  getUnitList()
  // hack, 在table创建出来之后再去调用
  proxy.$nextTick(() => {
    if (props.showStock) {
      tableInfo.value.fieldList.push({
        label: '库存数量',
        value: 'stockQty',
        type: 'column',
        formatter: proxy.$fn.qtyFormatter,
      })
    }
    if (props.showSupplierName) {
      tableInfo.value.fieldList.splice(3, 0, {
        label: '供应商名称',
        value: 'supplierName',
        minWidth: 150,
        type: 'slot',
      })
    }
    if (props.type == 'update') {
      tableInfo.value.data = [props.row]
    } else {
      getList()
    }
  })
})

// 获取列表
function getList() {
  tableInfo.value.refresh = Math.random()
}
function search() {
  tableInfo.value.initCurpage = Math.random()
  tableInfo.value.refresh = Math.random()
}
//获取计量单位列表
function getUnitList() {
  getUnitAll().then((resp) => {
    if (resp && resp.success && resp.data && resp.data.length > 0) {
      listTypeInfo.value.unitList = resp.data.map(function (item) {
        return { key: item.name, value: item.id + '' }
      })
    }
  })
}
function batchSetting() {
  if (!selectRow.value || !selectRow.value.length) {
    proxy.$message.warning('请至少选择一条数据')
    return
  }
  selectRow.value.forEach((item) => {
    item.periodStart = filterInfo2.value.query.periodStart
    item.periodEnd = filterInfo2.value.query.periodEnd
  })
  console.log(filterInfo2.value.query)
}
function save() {
  if (!selectRowIds.value.length && props.type == 'add') {
    proxy.$message({
      message: `请选择产品`,
      type: 'warning',
    })
    return
  }
  proxy.$refs['assetAmortizationDeptTableForm'].validate((valid) => {
    if (valid) {
      let params = []
      if (props.type == 'update') {
        selectRow.value = [tableInfo.value.data[0]]
      }
      let isDate = selectRow.value.find((i) => i.periodStart >= i.periodEnd)
      if (isDate) {
        proxy.$message({
          message: `约定量期间开始日期不能大于等于结束日期`,
          type: 'warning',
        })
        return
      }
      if (props.type == 'update') {
        params = {
          productId: tableInfo.value.data[0].productId,
          periodStart: tableInfo.value.data[0].periodStart,
          periodEnd: tableInfo.value.data[0].periodEnd,
          agreeLimit: tableInfo.value.data[0].agreeLimit,
          unitRatio: tableInfo.value.data[0].unitRatio,
          preparationUnit: tableInfo.value.data[0].preparationUnit,
          preparationQty: tableInfo.value.data[0].preparationQty,
          id: props.row.id,
        }
      } else {
        console.log(1111111111)
        console.log(selectRow.value)
        params = selectRow.value.map((i) => {
          return {
            productId: i.productId,
            periodStart: i.periodStart,
            periodEnd: i.periodEnd,
            agreeLimit: i.agreeLimit,
            unitRatio: i.unitRatio,
            preparationUnit: i.preparationUnit,
            preparationQty: i.preparationQty,
          }
        })
      }

      let api =
        props.type == 'add'
          ? agreeQuantityProductAdd
          : agreeQuantityProductUpdate
      api(params).then((res) => {
        if (res && res.success) {
          proxy.$message({
            message: `操作成功`,
            type: 'success',
          })
          handleClose()
          emits('callback', selectRow.value)
        }
      })
    }
  })
}
function handleEvent(event, data) {
  switch (event) {
    case 'tableClickRow':
      selectRow.value = data
      selectRowIds.value = data.map((i) => i.id)
      break
    case 'tableCheck':
      selectRow.value = data
      selectRowIds.value = data.map((i) => i.id)
      break
  }
  console.log(selectRowIds.value)
}
// 关闭弹窗前的回调
function handleClose() {
  shows.value = false
  emits('reset')
}
function preparationDoseChange(e, row, index) {
  row['preparationQty'] = (row['unitRatio'] || 0) * (row['agreeLimit'] || 0)
}
</script>

<style scoped></style>
